<?php
/*******************************************************************************

	/lib/dapi/airAuth.ps
	接口库.其它

	author: scumyang@gmail.com
	create: 2016-12-12

*******************************************************************************/
require_once 'dapi_conf.ps';

class dapi_airAuth extends ClassFinder_Action
{
	public function __construct( &$__config )
	{
		global $USER, $WEBAPP;
		//$__config->apiConf = $WEBAPP->attr( 'UCMS_conf' );
		parent::__construct( $__config );
	}

	// login
	// login?action=signIn&cpnum=18621815200&captcha=1234&gw_address=192.168.2.1&gw_port=2060&gw_id=test1&url=http://www.baidu.com/
	// login/?gw_id=00d011223344&gw_sn=1234942570128&gw_address=172.18.163.1&gw_port=2060&ip=172.18.163.109&mac=4c:2b:48:ac:55:6a&ssid=ap-test&url= http%3A%2F%2Fwww%2Eqq%2Ecom%2F
	public function login( $args=null )
	{
		global $USER, $WEBAPP, $HELPER;

		do
		{
			// 检查传入参数
			$gwID = $args->attr( BAS_PARAM_GW_ID );
			$gwSN = $args->attr( BAS_PARAM_GW_SN );
			$gwAddr = $args->attr( BAS_PARAM_GW_ADDR );
			$gwPort = $args->attr( BAS_PARAM_GW_PORT );
			$userIP = $args->attr( BAS_PARAM_USER_IP );
			$userMAC = $args->attr( BAS_PARAM_USER_MAC );
			$userURL = $args->attr( BAS_PARAM_USER_URL );
			$userSSID = $args->attr( BAS_PARAM_SSID );
			$action = $args->attr('action');

			__SQLInjectCheck( $args->attrs() );

			if( empty( $gwAddr ) || empty( $gwPort ) || empty( $gwID ) )
			{
				G_EXIT( "缺少路由参数" );
			}

			switch( $action )
			{
				case 'signIn':
				{
					$authOk = false;
					$cpnum = $args->attr('cpnum');
					$captcha = $args->attr('captcha');

					if( empty( $cpnum ))
					{
						$this->success( 0 );
						$this->msg( '必须指定手机号' );
						break;
					}

					// 检查手机号是否有记录
					$sql = "SELECT * FROM `enduser` WHERE cpnum='$cpnum' OR cpnum2='$cpnum'";
					$rs = $HELPER->dao()->query( $sql );

					// 若无记录则添加
					if( $rs->rowCount == 0 )
					{
						if( empty( $captcha ))
						{
							$this->success( 0 );
							$this->msg( '此号码首次登入，需要验证' );
							$this->retval->code = 'E601';
						}

						else if( $USER->attr('cert_captcha_cpnum') === $cpnum &&
									$USER->attr('cert_captcha_val') === $captcha )
						{
							$cpOperator;
							if( preg_match( "/^(134|135|136|137|138|139|147|150|151|152|157|158|159|178|182|183|184|187|188)/", $cpnum ) ) $cpOperator = '移动';
							else if( preg_match( "/^(130|131|132|155|156|185|186|145|176)/", $cpnum ) ) $cpOperator = '联通';
							else if( preg_match( "/^(133|153|177|180|181|189)/", $cpnum ) ) $cpOperator = '电信';

							// 保存数据
							$pea = new CSQLPea( 'enduser' );
							$pea->set( 'create_time', CUtils::getCurDateTime() )
								->set( 'creater_id', 0 )
								->set( 'gw_address', $gwAddr )
								->set( 'gw_port', $gwPort )
								->set( 'gw_id', $gwID )
								->set( 'gw_sn', $gwSN )
								->set( 'mac', $userMAC )
								->set( 'ip', $userIP )
								->set( 'url', $userURL )
								->set( 'ssid', $userSSID )
								->set( 'cpnum', $cpnum )
								->set( 'cpoperator', $cpOperator )
								;

							$sql = $pea->toSQL( SQL_INSERT );
							$HELPER->dao()->query( $sql );

							$this->success( 1 );
							$this->msg( '新号码，认证通过' );
							$authOk = true;
						}

						else
						{
							$this->success( 0 );
							$this->msg( '验证码不正确，请核对后重新输入' );
							$this->retval->code = 'E611';
						}
					}

					// 若已有记录
					else
					{
						$this->success( 1 );
						$this->msg( '已有号码, 认证通过' );
						$authOk = true;
					}

					if( $authOk )
					{
						// 生成响应
						$authToken = md5( $gwAddr . $gwPort . CUtils::newGUID( '9999999999' ));
						$redirURL = "http://$gwAddr:$gwPort/wifidog/auth?token=$authToken";

						// 保存数据
						$pea = new CSQLPea( 'enduser' );
						$pea->set( 'update_time', CUtils::getCurDateTime() )
							->set( 'updater_id', 0 )
							->set( 'status', '1' )
							->set( 'auth_token', $authToken )
							->setCase( "cpnum='$cpnum'" )
							;

						$sql = $pea->toSQL( SQL_UPDATE );
						$HELPER->dao()->query( $sql );

						//header( "Location: $redir" );
						$this->retval->redir = $redirURL;
					}

				} break;

				default:
				{
					// 放入会话
					$_SESSION['AUTH_INFO'] = $args;
					$_SESSION['AUTH_INFO']->attr('status', 0 );
					$_SESSION['AUTH_INFO']->attr('target_url', $userURL );

					// 登录页面
					$routeInfo = $args->toQueryString( '' );
					$html = $WEBAPP->attr('dapiDir') . "/WebAssets/airAuth_login.ps";
					include_once $html;
					exit;

				} break;
			}

			//$this->success( 1 );
			//$this->retval->responseJSON = new CAttrMixed( array('guid' => CUtils::newGUID( '', $type ) ));

		} while(0);

		return $this->retval;
	}

	// depCheck
	public function depCheck( $args=null )
	{
		global $USER, $WEBAPP, $HELPER;

		do
		{
			$R = new stdClass();
			//$R->snmpget = __checkFunc( 'snmpget' );
			//$R->snmpwalk = __checkFunc( 'snmpwalk' );
			//$R->snmpwalkoid = __checkFunc( 'snmpwalkoid' );
			$R->socket_create = __checkFunc( 'socket_create' );
			$R->socket_connect = __checkFunc( 'socket_connect' );
			$R->socket_set_option = __checkFunc( 'socket_set_option' );
			$R->socket_sendto = __checkFunc( 'socket_sendto' );
			$R->socket_recvfrom = __checkFunc( 'socket_recvfrom' );
			$R->SoapClient = __checkClass( 'SoapClient' );
			$R->__soapcall = __checkMethod( 'SoapClient', '__soapcall' );

			$this->success( 1 );
			$this->retval->responseJSON = new CAttrMixed( $R );

		} while(0);

		return $this->retval;
	}

	// testCase
	// test?gw_id=00d011223344&gw_sn=1234942570128&gw_address=172.18.163.1&gw_port=2060&ip=172.18.163.109&mac=4c:2b:48:ac:55:6a&ssid=ap-test&url=http://www.baidu.com/
	public function testCase( $args=null )
	{
		global $USER, $WEBAPP, $HELPER;

		do
		{
			// 获取传入参数
			$gwID = $args->attr( BAS_PARAM_GW_ID );
			$gwSN = $args->attr( BAS_PARAM_GW_SN );
			$gwAddr = $args->attr( BAS_PARAM_GW_ADDR );
			$gwPort = $args->attr( BAS_PARAM_GW_PORT );
			$userIP = $args->attr( BAS_PARAM_USER_IP );
			$userMAC = $args->attr( BAS_PARAM_USER_MAC );
			$userURL = $args->attr( BAS_PARAM_USER_URL );
			$userSSID = $args->attr( BAS_PARAM_SSID );

			/*$urlParam =
				  BAS_PARAM_GW_ID . "=$GatewayID&"
				. BAS_PARAM_USER_IP . "=$UserIP&"
				. BAS_PARAM_USER_MAC . "=$UserMAC"
				;*/
			$html = $WEBAPP->attr("dapiDir") . "/WebAssets/airAuth_testCase.ps";
			include_once $html;
			exit;

		} while(0);

		return $this->retval;
	}

	// auth
	// auth/?gw_id=00d012344561&gw_sn=1234942570128&stage=login&ip=172.18.163.22&mac=b8:ac:6f:40:1c:a9&token=1234&incoming=0&outgoing=0&action=portal
	public function auth( $args=null )
	{
		global $USER, $WEBAPP, $HELPER;

		do
		{
			// 检查传入参数
			$stage = $args->attr('stage');	// counter|login|logout
			$ip = $args->attr('ip');
			$mac = $args->attr('mac');
			$token = $args->attr('token');
			$incoming = $args->attr('incoming');
			$outgoing = $args->attr('outgoing');
			$gw_id = $args->attr('gw_id');

			__SQLInjectCheck( $args->attrs() );

			if( empty( $token ) )
			{
				die( "Auth: 0" );
			}

			// 检查 Token 是否存在
			$sql = "SELECT * from `enduser` WHERE `auth_token`='$token' limit 1";
			$rs = $HELPER->dao()->query( $sql );
			if( $rs->rowCount == 0 )
			{
				die( "Auth: 0" );
			}

			else
			{
				// 保存数据
				$pea = new CSQLPea( 'enduser' );
				$pea->set( 'uptime', CUtils::getCurDateTime() )
					->set( 'update_time', CUtils::getCurDateTime() )
					->set( 'updater_id', 0 )
					->set( 'status', '1' )
					->set( 'mac', $mac )
					->set( 'ip', $ip )
					->set( 'gw_id', $gw_id )
					->setCase( "cpnum='" . $rs->rows[0]->cpnum . "'" )
					;

				$sql = $pea->toSQL( SQL_UPDATE );
				$HELPER->dao()->query( $sql );

				die( "Auth: 1" );
			}

			exit;

		} while(0);

		return $this->retval;
	}

	// ping
	// ping?gw_id=test1&sys_uptime=242434545&sys_memfree=280000&sys_load=23.456&wifidog_uptime=242589200
	public function ping( $args=null )
	{
		global $USER, $WEBAPP, $HELPER;

		do
		{
			// 检查传入参数
			$sys_uptime = $args->attr('sys_uptime');
			$sys_memfree = $args->attr('sys_memfree');
			$sys_load = $args->attr('sys_load');
			$wifidog_uptime = $args->attr('wifidog_uptime');
			$gw_id = $args->attr('gw_id');

			__SQLInjectCheck( $args->attrs() );

			// 检查 Token 是否存在
			die( "Pong" );

		} while(0);

		return $this->retval;
	}

	// portal
	// portal?gw_id=test1
	public function portal( $args=null )
	{
		global $USER, $WEBAPP, $HELPER;

		do
		{
			// 检查传入参数
			$gw_id = $args->attr('gw_id');

			__SQLInjectCheck( $args->attrs() );

			$authInfo = @$_SESSION['AUTH_INFO'];
			if( !empty( $authInfo ))
			{
				$url = $authInfo->attr('target_url');

				// 神州小节点设备入口
				$url = 'http://192.168.100.90/';
				header( "Location: $url" );
			}
			else
			{
				$this->success( 0 );
				$this->msg( "portal 接口必须在认证通过后调用" );
			}

		} while(0);

		return $this->retval;
	}

	// 获取短信验证码
	public function getSmsCaptcha( $args=null )
	{
		global $USER, $WEBAPP, $HELPER, $__swatPHPDir;

		do
		{
			// 检查传入参数
			$cpnum = $args->attr('cpnum');
			$r = preg_match( "/^1[34578]{1}\d{9}$/", $cpnum );
			if( $r == 0 )
			{
				$this->msg( '手机号无效' );
				break;
			}

			// 避免频繁发送 (120 秒)
			$lastSmsTs = $USER->attr('cert_captcha_timestamp');
			if( !empty( $lastSmsTs )
			 	&& ( time() - $lastSmsTs < 60 ))
			{
				$this->msg( '获取短信验证码太频繁, 请稍后再操作！' );
				break;
			}

			// 发送短信验证码
			{
				require_once "$__swatPHPDir/ext/api-sms-sdk.ps";

				$captcha = str_pad( mt_rand( 1, 10000 ), 4, '0', STR_PAD_BOTH );

				if( 1 )
				{
					// 验证码类别
					$kind = $args->attr('kind');
					$kind = 'signIn';

					switch( $kind )
					{
						// 修改资料
						case 'modify':
							$smsText = "验证码：$captcha , 有效时间 10 分钟，用于修改乐创网会员资料。（为保护您的隐私安全，请勿向他人提供此短信验证码）【AirSpark】";
							break;

						// 登录
						case 'signIn':
							$smsText = "验证码: $captcha 用于登入认证（为保护您的隐私安全，请勿向他人提供此短信验证码）【AirSpark】";
							break;

						// 默认: 注册
						case 'signUp':
						default:
							$smsText = "注册验证码：$captcha , 有效时间 10 分钟，用于注册乐创网会员。（为保护您的隐私安全，请勿向他人提供此短信验证码）【AirSpark】";
					}

					$sms = new CSms( 'airAuth', 'airauth6556' );
					//$R = $sms->getBalance();
					$R = $sms->submitSms( $cpnum, $smsText );
					//CUtils::var_dump($R);
					//__DUMP($R,1);
				}

				// 更新 Session
				$USER->attr('cert_captcha_type', 'sms');
				$USER->attr('cert_captcha_kind', $kind);
				$USER->attr('cert_captcha_cpnum', $cpnum );
				$USER->attr('cert_captcha_val', $captcha);
				$USER->attr('cert_captcha_timestamp', time());

				$this->success( 1 );
				$this->retval->captcha = $captcha;
				$this->msg( '验证码已发送至手机, 请在 10 分钟内完成验证' );
				//session_cache_expire()
			}

		} while(0);

		return $this->retval;
	}
}
?>
